<?php
namespace app\api\controller\admin;

use app\admin\model\Admin;
use app\admin\model\dts\point\task\Log;
use app\common\controller\TApi;
use think\Db;

class Point extends TApi {

    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    //----------------------------------巡检---------------------------------------

    //巡检点位任务
    public function poinTaskList() {
        
        $type = $this->request->get('type');
        $query = $type != '' ? ['log.status' => $type] : ['log.status' => ['<>', Log::STATUS_3]];
        
        $admin = $this->auth->getAdmininfo();
        $query1 = ['log.admin_id' => $admin['id']];
        if($this->auth->isAdmin()) {
            $query1 = [];
        }

        $page = $this->request->get('page', 1);
        $pagesize = $this->request->get('pagesize', 10);        

        $list = Db::name('dts_point_task_log')->alias('log')
        ->field('log.*,pg.name as groupname,pg.location,task.name as taskname,time.name as timename')
        ->join([
            ['dts_point_grouping pg', 'pg.id = log.point_grouping_id', 'left'],
            ['dts_point_task task', 'task.id = log.point_task_id', 'left'],
            ['dts_point_time time', 'time.id = task.point_time_id', 'left']
        ])
        ->where(array_merge($query, $query1))
        ->paginate($pagesize, false, ['page' => $page]);

        $this->success('success', $list);
    }

    //巡检扫码
    public function pointScan() {
        $admin = $this->auth->getAdmininfo();

        $barcode = $this->request->post('barcode');
        $query = ['barcode.identifier' => $barcode, 'log.status' => Log::STATUS_1, 'log.nottime' => date('Y-m-d', time())];

        $taskLog = Db::name('dts_point_task_log')->alias('log')
        ->field('log.id,log.admin_id,pg.name,pg.location,barcode.identifier')
        ->join([
            ['dts_point_grouping pg', 'pg.id = log.point_grouping_id'],
            ['dts_config_barcode barcode', 'barcode.id = pg.config_barcode_id'],
        ])
        ->where($query)
        ->find();

        if(!$taskLog) {
            $this->error('点位巡检未开启');
        }
        if($taskLog['admin_id'] != $admin['id']) {
            $this->error('点位巡检人不匹配');
        }

        $this->success('success', $taskLog);
    }

    //巡检提交
    public function pointCheck() {

        $logId = $this->request->post('logId');
        $barcode = $this->request->post('barcode');
        
        $taskLog = Db::name('dts_point_task_log')->alias('log')
        ->field('log.id,log.admin_id,pg.name,pg.location,barcode.identifier')
        ->join([
            ['dts_point_grouping pg', 'pg.id = log.point_grouping_id'],
            ['dts_config_barcode barcode', 'barcode.id = pg.config_barcode_id'],
        ])
        ->where(['log.id' => $logId])
        ->find();

        if(!$taskLog || $taskLog['identifier'] != $barcode) {
            $this->error('巡检码不一致');
        }

        $status = $this->request->post('status', 0);
        $category = $this->request->post('category');
        $severity = $this->request->post('severity');
        $examineId = $this->request->post('examineId');
        $files = $this->request->post('files');
        $remark = $this->request->post('remark');

        if($status && $category == 'repair') {//维修
            !$severity || !$files ? ajaxerror('提交维修信息') : '';
        }

        if($status && $category == 'patrol') {//巡查
            !$severity || !$examineId || !$files ? ajaxerror('提交巡查信息') : '';
        }

        $admin = $this->auth->getAdmininfo();
        $dept = $this->auth->getDeptinfo();
        if(!$dept) {
            $this->error('未绑定部门信息');
        }

        __db(function() use($admin, $dept, $taskLog, $status, $category, $severity, $examineId, $files, $remark) {


            //更新任务
            \app\admin\model\dts\point\task\Log::where('id', $taskLog['id'])->update(['status' => Log::STATUS_3, 'finishtime' => date("Y-m-d H:i:s", time())]);
            
            $apiService = new \app\api\controller\Service;

            if($status && $category == 'repair') {//维修
                $data = [
                    'admin_id' => $admin['id'], 'deptname' => $dept['name'], 'category' => 'inspect', 'related_id' => $taskLog['task_id'], 
                    'name' => $taskLog['name'], 'location' => $taskLog['location'], 'severity' => $severity, 'describes' => $remark, 'files' => $files
                ];

                $db = \app\admin\model\dts\fault\Repair::create($data);
                $row = $db->getData();

                //查询是分配主任的人员
                $todoIdArr = [];
                $list = $apiService->specialList(628);
                if($list) {
                    //待办事项
                    foreach($list as $item) {
                        $todo = $apiService->savetodoitem($taskLog['location'].'异常', $category, $item['id'], $row['id']);
                        $todoIdArr[] = $todo['id'];
                    }
                }
                if($todoIdArr) {
                    \app\common\model\dts\fault\Repair::where('id', $row['id'])->update(['todo_ids' => join(',', $todoIdArr)]);
                }                
            }

            if($status && $category == 'patrol') {//巡查
                $data = [
                    'admin_id' => $admin['id'], 'deptname' => $dept['name'], 'severity' => $severity, 'location' => $taskLog['location'], 
                    'forcause' => $remark, 'images' => $files, 'examine_dept_id' => $examineId
                ];
                //代办事项
                $todo = $apiService->savetodoitem($taskLog['location'].'异常', $category, $examineId);
                $data['todo_id'] = $todo['id'];

                \app\admin\model\dts\approve\Patrol::create($data);
            }
        });

        $this->success('success');
    }
    
    //巡检记录
    public function pointCheckLog() {

        $query = ['log.status' => Log::STATUS_3];
        if(!$this->auth->isAdmin()) {
            $admin = $this->auth->getAdmininfo();
            $query['log.admin_id'] = $admin['id'];
        }

        $page = $this->request->get('page', 1);
        $pagesize = $this->request->get('pagesize', 10);

        $list = Db::name('dts_point_task_log')->alias('log')
        ->field('log.*,pg.name as groupname,pg.location,task.name as taskname,time.name as timename')
        ->join([
            ['dts_point_grouping pg', 'pg.id = log.point_grouping_id', 'left'],
            ['dts_point_task task', 'task.id = log.point_task_id', 'left'],
            ['dts_point_time time', 'time.id = task.point_time_id', 'left']
        ])
        ->where($query)
        ->paginate($pagesize, false, ['page' => $page]);

        $this->success('success', $list);
    }

    //------------------------------巡检绑定-------------------------------------------


    //巡检点位
    public function pointLocation() {
        $page = $this->request->get('page', 1);
        $pagesize = $this->request->get('pagesize', 10);

        $list = Db::name('dts_point_grouping')->alias('pg')
        ->field('pg.*,barcode.identifier,barcode.fileurl')
        ->join('dts_config_barcode barcode', 'barcode.id = pg.config_barcode_id', 'left')
        ->paginate($pagesize, false, ['page' => $page]);

        $this->success('success', $list);
    }

    
    //绑定点位
    public function bindPoint() {

        $identifier = $this->request->post("identifier");
        $barcode = \app\admin\model\dts\config\Barcode::where('identifier', $identifier)->find();
        if(!$barcode) {
            $this->error("二维码有误");
        }
        if($barcode['status'] == 1) {
            $this->error("二维码已使用");
        }
        $pointId = $this->request->post("pointId");
        if(!$pointId) {
            $this->error('请选择绑定点位');
        }

        __db(function() use($pointId, $barcode) {
            \app\admin\model\dts\config\Barcode::where('id', $barcode['id'])->update(['status' => 1]);
            \app\admin\model\dts\point\Grouping::where('id', $pointId)->update(['config_barcode_id' => $barcode['id']]);
        });
        
        $this->success('success');
    }
    
}